package wickethub.web.components.autocompleter;

import org.apache.wicket.ResourceReference;
import org.apache.wicket.behavior.AbstractAjaxBehavior;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.resources.JavascriptResourceReference;

public class AutocompleterBehavior extends AbstractAjaxBehavior {
	
	private final String dataId;
	
	public AutocompleterBehavior(String dataId) {
		this.dataId = dataId;
	}

	private static final ResourceReference AUTOCOMPLETER_JAVASCRIPT = 
		new JavascriptResourceReference(AutocompleterBehavior.class, "autocompleter.js");
	
	private static final ResourceReference AUTOCOMPLETER_LOCAL_JAVASCRIPT = 
		new JavascriptResourceReference(AutocompleterBehavior.class, "autocompleter-local.js");

	private static final ResourceReference OBSERVER_JAVASCRIPT = 
		new JavascriptResourceReference(AutocompleterBehavior.class, "observer.js");

	private static final ResourceReference MOOTOOLS_JAVASCRIPT = 
		new JavascriptResourceReference(AutocompleterBehavior.class, "mootools-trunk.js");
	
	
	@Override
	protected void onBind() {
		super.onBind();
		getComponent().setOutputMarkupId(true);
	}
	
	public void onRequest() {
	}
	
	@Override
	public void renderHead(IHeaderResponse response) {
		super.renderHead(response);
		response.renderJavascriptReference(MOOTOOLS_JAVASCRIPT);
		response.renderJavascriptReference(OBSERVER_JAVASCRIPT);
		response.renderJavascriptReference(AUTOCOMPLETER_JAVASCRIPT);
		response.renderJavascriptReference(AUTOCOMPLETER_LOCAL_JAVASCRIPT);
		response.renderOnDomReadyJavascript("new Autocompleter.Local('" + getComponent().getMarkupId() + "', " + dataId + ", { 'minLength': 2, 'selectMode': 'type-ahead', 'delay': '0', 'multiple': true });");
	}

}
